package string;

import org.junit.Test;

/**
 * @Description 125. 验证回文串 https://leetcode.cn/problems/valid-palindrome/
 * @Author Firenut
 * @Date 2023-02-17 13:33
 */
public class T125_isPalindrome {
    @Test
    public void test() {
//        String str = "race a car";
        String str = "A man, a plan, a canal: Panama";
        System.out.println(isPalindrome(str));
    }

    // 法2: 双指针左右扫描并比较是否相等
    public boolean isPalindrome1(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
                sb.append(ch);
            } else if (ch >= 'A' && ch <= 'Z') {
                sb.append((char) ('a' + ch - 'A'));
            }
        }
        int i = 0, j = sb.length() - 1;
        while (i < j) {
            if (sb.charAt(i) != sb.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

    // 法1: 先删掉非数字字母的字符，然后反转比较(注意一些api调用的细节)
    public boolean isPalindrome(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) {
                sb.append(ch);
            } else if (ch >= 'A' && ch <= 'Z') {
                sb.append((char) ('a' + ch - 'A'));
            }
        }
//        StringBuffer sbrev = sb.reverse(); // 使用reverse()会修改本身的字符串，导致其反转
        StringBuffer sbrev = new StringBuffer(sb).reverse();
//        System.out.println(sb.toString());
//        System.out.println(sbrev.toString());
        return sb.toString().equals(sbrev.toString()); // StringBuffer没有重写equals(),比较的是地址
    }
}
